package drugdealer.control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import drugdealer.data.UsuarioDAO;

/**
 * Servlet implementation of class LoginRedirect.
 * 
 * When the Tomcat Security Realm login is successful the flow is
 * redirected to this servlet (URI: /loginRedirect) which sets
 * the session with user details and depending on the user type
 * it sets the redirect page. 
 * 
 * @author dave
 */
@WebServlet("/loginRedirect")
@SuppressWarnings("serial")
public class LoginRedirectServlet extends HttpServlet {

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginRedirectServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("LoginRedirectServlet.doGet()");

		// Get current user name
		String email = request.getRemoteUser();
		HttpSession session = request.getSession();
		String url = "";

		// Assign url only if it was not assigned before
		if (session.getAttribute("tipoUsuario") == null) {
			// If user is logged in
			if (!email.isEmpty()) {
				// Set current user email (id) in session
				session.setAttribute("email", email);

				// Set current user type in session
				String userType = UsuarioDAO.getTipo(email);

				// Set redirect url corresponding to the user type
				if (userType.equals("paciente")) {
					session.setAttribute("tipoUsuario", "paciente");
					url = "/seguranca/paciente/index.jsp";
				} else if (userType.equals("medico")) {
					session.setAttribute("tipoUsuario", "medico");
					url = "/seguranca/medico/index.jsp";
				} else if (userType.equals("admin")) {
					session.setAttribute("tipoUsuario", "admin");
					url = "/seguranca/administrador/index.jsp";
				}
			}
			// If user is not logged in
			else {
				// Return to the home page
				url = "/";
			}
		} else {
			url = "/seguranca/" + session.getAttribute("tipoUsuario") + "/index.jsp";
		}

		response.sendRedirect(url);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
